#include <Editor/StdAfx.h>
#include "FileFunctions.h"
#include "GameToolApp.h"

bool IsSubPath(const wxFileName& parent, const wxFileName& sub)
{
	assert(parent.IsAbsolute());
	assert(sub.IsAbsolute());
	if (parent.GetVolume()!= sub.GetVolume())
		return false;

	wxArrayString parentDirs = parent.GetDirs();
	wxArrayString subDirs = sub.GetDirs();
	unsigned psize = parentDirs.size();
	unsigned ssize = subDirs.size();
	if (psize > ssize)
		return false;

	for(unsigned i=0; i<psize; i++)
	{
		if (parentDirs[i] != subDirs[i])
			return false;
	}
	return true;
}

void CopyTargetToDataFolder(const wxString& path, const wxString& targetDirectory, wxWindow* parent)
{
	wxFileName imageFilename(path);
	wxFileName dataPath(wxStandardPaths().GetExecutablePath());
	dataPath.AppendDir(wxT("Data"));
	bool subpath = IsSubPath(dataPath, imageFilename);
	if (!subpath)
	{
		wxMessageDialog ask(parent, 
			_("Selected image file is not under the resource folder. \
				Do you want to copy the image file to the resource folder(Data\\terrains)?"), wxMessageBoxCaptionStr, 
			wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION);
		if (ask.ShowModal() == wxID_YES)
		{
			wxFileName destFile(wxStandardPaths().GetExecutablePath());
			destFile.SetName(imageFilename.GetName());
			destFile.SetExt(imageFilename.GetExt());
			destFile.AppendDir(wxT("Data"));
			destFile.AppendDir(targetDirectory);
			bool dirExist;
			dirExist = destFile.DirExists();
			if (!dirExist)
			{
				wxString destDir;
				destDir = destFile.GetPath();
				if (wxMkdir(destDir) == false)
				{
					wxString msg = wxString::Format(_("Creating directory(%s) is failed."), destDir.c_str());
					wxGetApp().Message(msg);
				}
				else
				{
					dirExist = true;
				}
			}
			if (dirExist)
			{
				// file exist check
				bool fileExist = destFile.FileExists();
				if (!fileExist)
				{
					bool copySuccess = wxCopyFile(imageFilename.GetFullPath(), destFile.GetFullPath(), true);
					if (!copySuccess)
					{
						wxGetApp().Message(_("File copy failed. There may be a file that has the same name. Please change the source file name and retry.") );
					}
					else
					{
						wxString msg = wxString::Format(_("file %s is copied to %s"), imageFilename.GetFullPath().c_str(), destFile.GetFullPath().c_str());
						wxGetApp().Message(msg);
					}
				}
				else
				{
					wxString strmsg = wxString::Format(
						_("file name %s already exists in the data folder. The existing file is used instead of user selected file."),
						destFile.GetFullName().mb_str());
					wxGetApp().Message(strmsg);
				}
			}
		}
	}
}